/**
 * Company
 * Copyright (C) 2004-2018 All Rights Reserved.
 */
package com.idefav.springdemo2.aop.basic.proxy;

import com.alibaba.fastjson.JSON;
import com.idefav.springdemo2.aop.beans.User;
import com.idefav.springdemo2.aop.services.UserService;
import com.idefav.springdemo2.aop.services.impl.UserServiceImpl;
import org.junit.Test;
import sun.misc.ProxyGenerator;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author wuzishu
 * @version $Id JavaProxyDemo.java, v 0.1 2018-07-22 下午1:49 wuzishu Exp $$
 */

public class JavaProxyDemo {

    @Test
    public void javaProxyTest(){
        final UserServiceImpl userServiceImpl=new UserServiceImpl();

        // 生成Proxy对象
        UserService userService = (UserService) Proxy.newProxyInstance(JavaProxyDemo.class.getClassLoader(), new Class[]{UserService.class}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("前置通知");
                Object result=null;
                try {

                  result=   method.invoke(userServiceImpl, args);
                }
                catch (Exception ex){
                    System.out.println("异常通知");
                    ex.printStackTrace();
                }
                System.out.println("后置通知");
                return result;
            }
        });

        // 执行Proxy
        User user = userService.getUser();

        System.out.println("获取User:"+ JSON.toJSONString(user));
    }

    @Test
    public void javaProxyGeneratorClass() throws IOException {
        byte[] proxy0s = ProxyGenerator.generateProxyClass("proxy0", new Class[]{UserService.class}, Modifier.PUBLIC | Modifier.FINAL);
        Path path=new File(System.getProperty("user.dir")+"/target/proxy0.class").toPath();
        Files.write(path, proxy0s);

    }

}
